#include <Abracadabra/View/Tube.hpp>

namespace View
{

Tube::Tube(uint8_t size, sf::FloatRect rect)
	: size(size)
	, rects(size, sf::RectangleShape())
{
	float width = rect.width;
	float height = rect.height / this->size;

	for(uint8_t i = 0; i < this->size; ++i)
	{
		rects[i].setSize({width, height});
		rects[i].setPosition({rect.left, rect.top + (height * i)});
	}
}

void Tube::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
	for(uint8_t i = 0; i < this->size; ++i)
	{
		target.draw(this->rects[i]);
	}
}

void Tube::update(const std::vector<uint8_t>& dots)
{
	for(uint8_t i = 0; i < this->size; ++i)
	{
		sf::RectangleShape& dotRect = this->rects[size - 1 - i];

		std::optional<uint8_t> dot;

		if(dots.size() <= i)
		{
			dot = std::nullopt;
		}
		else
		{
			dot = dots[i];
		}
		this->updateDot(dotRect, dot);
	}
}

void Tube::updateDot(sf::RectangleShape& dotRect, std::optional<uint8_t> dot)
{
	dotRect.setTexture(&this->theme->dotsTexture);
	if(dot)
	{
		sf::IntRect textureRect = {this->theme->dotTextureW * dot.value(), 0, this->theme->dotTextureW, this->theme->dotTextureH};
		dotRect.setTextureRect(textureRect);
	}
	else
	{
		dotRect.setTextureRect({0, 0, 0, 0});
	}
}
}
